package com.share.domain.strategy.service.rule.tree.impl;

import com.share.domain.strategy.model.vo.RuleLogicCheckTypeVo;
import com.share.domain.strategy.model.vo.StrategyAwardStockKeyVo;
import com.share.domain.strategy.repository.IStrategyRepository;
import com.share.domain.strategy.service.armory.IStrategyDispatch;
import com.share.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.share.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 库存树节点
 */
@Component("rule_stock")
@Slf4j
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        //扣减商品库存动作
        log.info("规则过滤-库存扣减 userId:{},strategyId:{},awardId:{}",userId,strategyId,awardId);
        boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId,endDateTime);
        if(status){
            //写入延迟队列，延迟消费更新库存记录 [strigger的job updateStockJob下消费队列 更新数据库记录]
            repository.awardStockConsumeSendQueue(StrategyAwardStockKeyVo.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build());
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVo.TAKE_OVER)
                    .strategyAwardVo(DefaultTreeFactory.StrategyAwardVo.builder()
                            .awardId(awardId)
                            .awardRuleValue("")
                            .build())
                    .build();
        }

        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVo.TAKE_OVER)
                .build();
    }
}
